package com.mew.game.play;

import com.mew.common.dc.db.LoginoutService;
import com.mew.common.dc.redis.AucRedisService;
import com.mew.common.enm.ExitType;
import com.mew.common.rest.bo.MewSession;
import com.mew.common.rest.game.EnterRoomRequest;
import com.mew.common.rest.game.EnterRoomResponse;
import com.mew.common.rest.sas.EnterGameSasRequest;
import com.mew.common.rest.sas.ExitGameSasRequest;
import com.zebra.common.OnlineType;
import com.zebra.common.event.EventBusAsyncCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class EnterRoomService {

    @Autowired
    private LoginoutService loginoutService;
    @Autowired
    private AucRedisService aucRedisService;


    public EnterRoomResponse enterRoom(EnterRoomRequest request){
        MewSession session = aucRedisService.getSession(request.getUid());
        if (-9 == session.rioid){
            return doEnterRoom(request, session);
        }

        if (request.getType() == 3){
            return doReconnectRoom(request, session);
        }
        loginoutService.doExitRoom(session, ExitType.Repeat);

        EventBusAsyncCenter.post(EnterGameSasRequest.builder()
                .userId(request.getUid())
                .gameId(request.getGameId())
                .roomId(request.getRoomId())
                .build());
        return doEnterRoom(request, session);

    }

    private EnterRoomResponse doEnterRoom(EnterRoomRequest request, MewSession session){
        doOnlineGame(request,  request.getType());
        return loadInfo(request);
    }

    private EnterRoomResponse doReconnectRoom(EnterRoomRequest request, MewSession session){
        doOnlineGame(request,  3);
        return loadInfo(request);
    }

    private void doOnlineGame(EnterRoomRequest request,  int enterType){
        MewSession other = new MewSession();
        other.gwsid = request.getGatewaySid();
        other.tk = aucRedisService.getToken();
        other.loc = request.getGameId();
        other.gsid = request.getServerId();
        other.onl =  OnlineType.Online.value();

        other.gid =  request.getGameId();
        other.rid = request.getRoomId();

        if (enterType != 3){
            other.initPlayInfo();
        }
        aucRedisService.onlineSession(request.getUid(), other);
    }

    private EnterRoomResponse loadInfo(EnterRoomRequest request){
       return EnterRoomResponse.builder()
               .errorState(200)
               .build();
    }

    public void exitGame(long userId, int exitType){
        MewSession session = aucRedisService.getSession(userId);
        loginoutService.exitRoom(userId, exitType);
        EventBusAsyncCenter.post(ExitGameSasRequest.builder()
                .userId(userId)
                .gameId(session.gid)
                .roomId(session.rid)
                .build());
    }
}
